package net.ulrice.mdls.richclient.monitor;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.swing.JComponent;
import javax.swing.JPanel;

import net.ulrice.mdls.services.Application;
import net.ulrice.module.impl.AbstractController;
import net.ulrice.module.impl.action.ModuleAction;
import net.ulrice.module.impl.action.UActionState;

public class MonitorController extends AbstractController {

	private JPanel view;
	private ApplicationRefreshTask applicationRefreshTask;
	private Application application;
	private ScheduledExecutorService threadPool;
	
	public MonitorController(Application application) throws IOException {
		this.view = new JPanel();
		this.application = application;
	}
	
	@Override
	public void postCreate() {
		super.postCreate();

		threadPool = Executors.newScheduledThreadPool(1);
		applicationRefreshTask = new ApplicationRefreshTask(this, application, new ViewCallback(view));
		startMonitoring();
	}
	
	@Override
	public JComponent getView() {
		return view;
	}
	
	@ModuleAction(actionId = "StartMonitoring", name = "Start Monitoring", iconName = "play.png")
	public void startMonitoring() {
		threadPool.scheduleAtFixedRate(applicationRefreshTask, 1, application.getRefreshRate(), TimeUnit.SECONDS);
	}
	
	@ModuleAction(actionId = "StopMonitoring", name = "Stop Monitoring", iconName = "stop.png", initiallyEnabled = false)
	public void stopMonitoring() {
		threadPool.shutdown();			
		setActionStates(new UActionState("StartMonitoring", true), new UActionState("StopMonitoring", false));
	}
}
